/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daoGenerico;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Ana
 */
public class DAOgenerico<T> {
    private final Class<T> c;
    public DAOgenerico(Class<T> c){
        this.c=c;
    }

    public DAOgenerico() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    public void add(T t){
        EntityManager em=new JPAManager().getManager();
        em.getTransaction().begin();
        em.persist(t);
        em.getTransaction().commit();
        em.close();
    }
    public void del(T t){
        EntityManager em=new JPAManager().getManager();
        em.getTransaction().begin();
        em.remove(em.merge(t));
        em.getTransaction().commit();
        em.close();
    }
    public void update(T t){
        EntityManager em=new JPAManager().getManager();
        em.getTransaction().begin();
        em.merge(t);
        em.getTransaction().commit();
        em.close();
    }
    public List<T> showall(){
        EntityManager em=new JPAManager().getManager();
        CriteriaQuery<T> q=em.getCriteriaBuilder().createQuery(c);
        
        List<T> l=em.createQuery(q).getResultList();
        em.close();
        
        return l;
    }
    
    public List<T> ListAll() {
        EntityManager em = new JPAManager().getManager();
        
        Query query;// = em.createQuery("SELECT o FROM Object o");
        
        try {
            return em.createQuery("SELECT e FROM" +c.getSimpleName()+ "e" ).getResultList();
            
        } catch (Exception e) {
            return null;
        } 
    }
    
    
    public T showthis(Long id){
        EntityManager em=new JPAManager().getManager();
        return (T) em.find(c, id);
    }
}
